from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker


class DbUtils(object):
    def __init__(self, uri):
        self.DBengine = create_engine(uri)

    def getCountSql(self, sql, pargm=None):
        """

        返回count语句的数量结果

        print("result:%s"%getCountSql("SELECT count(*) FROM zqt_doc"))
        :param sql:
        :return:
        """
        r = self.DBengine.execute(sql, pargm) if pargm else self.DBengine.execute(sql)
        ru = r.fetchall()[0][0]
        return ru

    def updateSql(self, sql, pargm=None):
        """

        执行更新语句

        :param sql:

        :return:

        """
        r = self.DBengine.execute(sql, pargm) if pargm else self.DBengine.execute(sql)
        return r.rowcount

    def getSelectSql(self, sql, pargm=None):
        """

        返回select语句的结果集

        :param sql:

        :return:

        """
        r = self.DBengine.execute(sql, pargm) if pargm else self.DBengine.execute(sql)
        return r.fetchall()

    def getSession(self):
        DB_Session = sessionmaker(bind=self.DBengine)
        session = DB_Session()
        return session

    def getCountSql_Session(self, session, sql, pargm=None):
        """

        返回count语句的数量结果

        print("result:%s"%getCountSql("SELECT count(*) FROM zqt_doc"))
        :param sql:
        :return:
        """
        r = session.execute(sql, pargm) if pargm else session.execute(sql)
        ru = r.fetchall()[0][0]
        return ru

    def updateSql_Session(self, session, sql, pargm=None):
        """

        执行更新语句

        :param sql:

        :return:

        """
        r = session.execute(sql, pargm) if pargm else session.execute(sql)
        return r.rowcount

    def getSelectSql_Session(self, session, sql, pargm=None):
        """

        返回select语句的结果集

        :param sql:

        :return:

        """
        r = session.execute(sql, pargm) if pargm else session.execute(sql)
        return r.fetchall()
